﻿unit ProcUtill;

interface

uses ShellApi,tlhelp32, psapi,WinSvc,Windows, Messages, SysUtils, Variants, Classes;
function LocateProcess(const ImageName: String): Integer;
procedure Kill(exe :string);
implementation

//.....................Получаем id процесса по имени приложения................
function LocateProcess(const ImageName: String): Integer;
var
 Snapshot,
 ProcessHandle,
 ModuleHandle,
 i: Integer;
 BytesRead: Cardinal;
 ProcessEntry: TProcessEntry32;
 ExeFile: String;
 PIDs: array[0..4095] of DWord;
begin
 Result := 0;
 Snapshot := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
 SetLength(ExeFile, Length(ImageName));
 if Snapshot <> 0 then
   begin
     // Processes enumeration loop for Windows 9x, Me, 2000
     // ToolHelp32 API
     ProcessEntry.dwSize := SizeOf(TProcessEntry32);
     if Process32First(Snapshot, ProcessEntry) then
       repeat
         if AnsiSameText(ImageName, ExtractFileName(ProcessEntry.szExeFile)) then
           begin
             Result := ProcessEntry.th32ProcessID;
             Break;
           end;
       until not Process32Next(Snapshot, ProcessEntry);
     CloseHandle(Snapshot);
   end
 else
   // Processes enumeration loop for Windows NT, 2000 PSAPI
   if EnumProcesses(@PIDs, SizeOf(PIDs), BytesRead) then
     begin
       for i := 0 to BytesRead shr 2 - 1 do
         begin
           ProcessHandle := OpenProcess(PROCESS_VM_READ or
             PROCESS_QUERY_INFORMATION, False, PIDs[i]);
           if ProcessHandle <> 0 then
             begin
               ExeFile := '';
               if EnumProcessModules(ProcessHandle, @ModuleHandle,
                    SizeOf(ModuleHandle), BytesRead) then
                 GetModuleBaseName(ProcessHandle, ModuleHandle, PChar(ExeFile),
                   Length(ExeFile) + 1);
               CloseHandle(ProcessHandle);
               if AnsiSameText(ImageName, ExeFile) then
                 begin
                   Result := PIDs[i];
                   Break;
                 end;
             end;
         end;
     end;
end;

{_______Убиваем процесс________________________________________________________}
procedure Kill(exe :string);
const
 PROCESS_TERMINATE = $0001;
 var
 ProcessHandle:THandle;
begin
 ProcessHandle:=OpenProcess(PROCESS_TERMINATE, FALSE, LocateProcess(exe));
 TerminateProcess(ProcessHandle,0);
end;
end.
